using System.Collections.Generic;
using System.Windows.Forms;

namespace EzDeploy.Core
{
    /// <summary>
    /// 
    /// </summary>
    public class DuplicateAssemblyNameCheck : ICommandCheck
    {
        private Dictionary<string, List<DeployGridItem>> _duplicateHash;
        bool _errorFound;

        public bool ErrorFound
        {
            get
            {
                return _errorFound;
            }
        }

        public void Check(IEnumerable<DeployGridItem> items, Project project)
        {
            _errorFound = false;
            _duplicateHash = new Dictionary<string, List<DeployGridItem>>();

            foreach (var item in items)
            {
                if (item.DeploymentType == DeploymentType.Exclude)
                    continue;

                if (!_duplicateHash.ContainsKey(item.AssemblyName.Name))
                {
                    var duplicates = this.CheckForDuplicate(items, item);
                    if (duplicates.Count > 0)
                    {
                        duplicates.Add(item);
                        _duplicateHash.Add(item.AssemblyName.Name, duplicates);
                    }
                }
            }

            _errorFound = _duplicateHash.Count > 0;
        }

        List<DeployGridItem> CheckForDuplicate(IEnumerable<DeployGridItem> items, DeployGridItem checkedItem)
        {
            var duplicateItems = new List<DeployGridItem>();

            foreach (var item in items)
            {
                if (item.DeploymentType == DeploymentType.Exclude)
                    continue;

                if (item.AssemblyName.FullyQualifiedPath == checkedItem.AssemblyName.FullyQualifiedPath)
                    continue;

                if (item.AssemblyName.Name == checkedItem.AssemblyName.Name)
                {
                    duplicateItems.Add(item);
                }
            }

            return duplicateItems;
        }


        public Form ResultForm
        {
            get { return new DuplicateAssemblyNameForm(_duplicateHash); }
        }

        public void Fix(Project project)
        {
            foreach (var kv in this._duplicateHash)
            {
                foreach (var item in kv.Value)
                    item.DeploymentType = DeploymentType.Exclude;
            }

            this.Reset();
        }

        public void Reset()
        {
            _errorFound = false;
            if (_duplicateHash != null)
                _duplicateHash.Clear();
        }
    }
}
